package cn.orange.ch11_graph;

import java.util.LinkedList;

/**
 * LC200.岛屿数量
 */
public class LC200 {
    private static final int[][] directions = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int ans = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
//                    dfs(grid, i, j);
                    bfs(grid, i, j);
                    ans++;
                }
            }
        }
        return ans;
    }

    private void bfs(char[][] grid, int i, int j) {
        int m = grid.length;
        int n = grid[0].length;
        LinkedList<int[]> que = new LinkedList<>();
        que.offer(new int[]{i, j});
        grid[i][j] = '0';
        while (!que.isEmpty()) {
            int size = que.size();
            for (int k = 0; k < size; k++) {
                int[] poll = que.poll();
                int x = poll[0];
                int y = poll[1];
                for (int[] dir : directions) {
                    int newX = x + dir[0];
                    int newY = y + dir[1];
                    if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == '1') {
                        que.offer(new int[]{newX, newY});
                        grid[newX][newY] = '0';
                    }
                }
            }
        }
    }

    private void dfs(char[][] grid, int i, int j) {
        int m = grid.length;
        int n = grid[0].length;
        if (i < 0 || i >= m || j < 0 || j >= n) {
            return;
        }
        if (grid[i][j] == '0') return;
        grid[i][j] = '0';
        for (int[] dir : directions) {
            int newX = i + dir[0];
            int newY = j + dir[1];
            dfs(grid, newX, newY);
        }
    }

    public static void main(String[] args) {
        LC200 alg = new LC200();
        char[][] grid = new char[][] {
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}
        };
        System.out.println(alg.numIslands(grid));
    }
}
